<script>
	//引入userSig加密算法
	import {
		genTestUserSig
	} from './common/GenerateTestUserSig.js';
	import userlist from './common/tim/user.js'
	//加载插件
	const txCall = uni.requireNativePlugin('HG-TxCall');
	import tim from './common/tim/tim.js'
	// const modal = uni.requireNativePlugin('modal');

	export default {
		data() {
			return {
				userinfo: [],
				target: [],
				liveStatus: false,
				txConfiged: false,
				callBack: () => {}
			}
		},
		mounted() {
			/**官网有很多关于关于sdk 其他的监听方法（比如：有新的消息，用户资料更新等等）
			 * 详情可对照： https://imsdk-1252463788.file.myqcloud.com/IM_DOC/Web/SDK.html
			 * 监听的含义：服务端发生了数据变更---前端全局可以接收到变更通知--前端就可以自动触发某个事件来更新相应数据
			 * */
			
			
			let userInfo = uni.getStorageSync('userInfo')
			console.log(userInfo)
			if (userInfo) {
				userInfo = JSON.parse(userInfo)
				var config = tim.genTestUserSig(userInfo.id.toString());
				let promise = this.tim.login({
					userID: userInfo.id.toString(),
					userSig: config.userSig
				});
				promise.then((res) => {
					//登录成功后 更新登录状态
					this.$store.commit("toggleIsLogin", true);
					//自己平台的用户基础信息
					uni.setStorageSync('userInfo', JSON.stringify(userInfo))
					//tim 返回的用户信息
					uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
					
				}).catch((err) => {
					console.warn('login error:----------', err); // 登录失败的相关信息
				});
			}
			// 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
			this.tim.on(this.$TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this);
			// 收到新消息
			this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage);
			// 会话列表更新
			this.tim.on(this.$TIM.EVENT.CONVERSATION_LIST_UPDATED, event => {
				this.$store.commit("updateConversationList", event.data);
			});
		},
		methods:{
			onReadyStateUpdate({name}) {
				const isSDKReady = name === this.$TIM.EVENT.SDK_READY ? true : false;
				//自动监听并更新 sdk 的ready 状态 （未登录是 notReady  登录后是ready）
				this.$store.commit("toggleIsSDKReady", isSDKReady);
				//sdk ready 后  肯定完成了登录操作    这里可以获取用户存储在im的基础信息/离线消息/黑名单列表
				console.log('++++++++++++++++++++++',this.tim)
				console.log(312312)
				let promise = this.tim.updateMyProfile({
					nick: userInfo.nickname,
					avatar: userInfo.avatar
				})
				
				console.log(312312)
				promise.then(res => {
					debugger
					console.info('------------------',res)
				}).catch(err => {
					debugger
					console.error('login error:----------', err); // 登录失败的相关信息
				})
			},
			
			onReceiveMessage({data: messageList}) {
				// this.handleAt(messageList);
				this.$store.commit("pushCurrentMessageList", messageList);
				console.log("messageList:",messageList)
				this.tim.getUserProfile({
					userIDList: [messageList[0].from]
				}).then(res => {
					console.log('1111111111111',res)
				}).catch(err => {
					console.log('2222222222222222',err)
				})
			},
			//根据消息列表请求聊天对象的用户信息 并完成数据拼接
			txConfig(_this) {
				if (undefined == _this.userinfo.id) {
					console.log("tx 当前用户id 为空");
					return;
				}
				var id = _this.userinfo.id + "";
				console.log("tx 当前用户id:" + id);
			
				var config = genTestUserSig(id);
				if (txCall != undefined) {
			
					txCall.config({
						"userId": id, //我的用户ID
						"userSig": "" + config.userSig, //UserSig的密钥
						"nickName": "" + _this.userinfo.nickname, //用户昵称
						"useDefaultRandomAvatar": true, //是否使用随机头像
						"userAvatar": "" + _this.userinfo.avatar, //头像地址
						"appid": "" + config.sdkAppID ,//腾讯云申请的appID
						"baseUrl":"http://zf.hualin688.com/api/api/",
						"api":"userMsgById"
					}, (ret) => {
						console.log("tx config" + ret);
						console.log(ret);
						console.log("tx " + ret.code + "," + ret.message);
						switch (ret.code) {
							case -93:
								this.$utils.showLayer("链接结束");
								this.txCloseCall();
							  break;
							case -94:
								this.$utils.showLayer("链接超时");
							  break;
							case -95:
								this.$utils.showLayer("对方忙");
							  break;
							case -96:
								this.$utils.showLayer("无应答");
							  break;
							case -97:
								this.$utils.showLayer("取消会话");
								this.txCloseCall();
							  break;
							case -98:
								this.$utils.showLayer("被拒绝");
							  break;
							case -99:
							  this.$utils.showLayer("没有提供ID");
							  break;
							case -100:
							  this.$utils.showLayer("未登陆");
							  break;
							default:
							  // this.$utils.showLayer(ret.message);
							  break;		
						}
					});
					console.log("tx configed");
				} else {
					console.log("请先配制插件");
				}
			
			},
			txCloseCall() {
				if (txCall) {
					txCall.closeCall();
					this.$utils.showLayer("结束");
					this.liveStatus = false;
					this.callBack();
				} else {
					console.log("请先配制插件");
				}
			},
			enterLiveRoom (_this) {
				if (txCall) {
					let {title, roomId, anchorId, roomName, anchorName, coverUrl, pusher_avatar} = _this.target;
					// type = type=== undefined || type==='' ? 'video' : type;
					// mode = mode=== undefined || mode==='' ? 'call' : mode;
					roomId = roomId=== undefined || roomId==='' ? 0 : roomId;
					this.callBack =  typeof _this.target.callback === 'function' ? _this.target.callback : () => {};
					txCall.enterLiveRoom({
						roomName:roomName,//房间名称
						roomId: roomId,//主播房间号s
						anchorId: anchorId,//主播id
						anchorName: anchorName,//主播名称
						coverUrl: coverUrl,//封面
						pusher_avatar: pusher_avatar,//主播头像
					});
				} else {
					console.log("请先配制插件");
				}
			},
			startLiveRoom (_this) {
				if (txCall) {
					let {title, roomId} = _this.target;
					roomId = roomId=== undefined || roomId==='' ? 0 : roomId;
					this.callBack =  typeof _this.target.callback === 'function' ? _this.target.callback : () => {};
					txCall.startLiveRoom({
						title: title,
						roomID: roomId,
					});
					this.liveStatus = true;
				} else {
					console.log("请先配制插件");
				}
			},
			 txLogOut() {
				if (txCall) {
					txCall.logOut();
				} else {
					console.log("请先配制插件");
				}
			},
			
			/**
			 * 呼叫用户
			 * @param {Object} _this
			 */
			txStartCall(_this) {
				console.log("目标用户id:" + _this.target.id + ",name:" + _this.target.nickname + ", head:" + _this.target.avatar);
				let {type, mode, roomId, target, callBack} = _this.target;
				type = type=== undefined || type==='' ? 'video' : type;
				mode = mode=== undefined || mode==='' ? 'call' : mode;
				roomId = roomId=== undefined || roomId==='' ? 0 : roomId;
				callBack =  typeof _this.callback === 'function' ? _this.callback : () => {};
				if (txCall) {
					txCall.startCall({
						"callType": type, //audio表示语音，video表示视屏通话
						"mode": mode, //call表示通话  meeting表示会议
						"roomId": roomId, //会议ID 房间号不存在，则自动创建
						"targetInfo": { //目标信息
						"userId": _this.target.id, //被呼叫方的ID
						"nickName": _this.target.nickname, //用户昵称
						"userAvatar": "" + _this.target.avatar, //头像地址 
						}
					});
				} else {
					console.log("请先配制插件");
				}
			},
		},
		onLaunch: function() {
			
			console.log('userlistuserlistuserlistuserlistuserlist')
			console.log(userlist)
			console.log('userlistuserlistuserlistuserlistuserlist')
			//中间凸起按钮
			this.userinfo = uni.getStorageSync('userinfo')
			uni.onTabBarMidButtonTap((e) => {

				console.log(this.userinfo)
				if (this.userinfo.boss == 0) {
					uni.showToast({
						title: '未认证，即将跳转至认证页面，认证后即可发布',
						duration: 2000,
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/selsectIdentity/selsectIdentity'
						})
					}, 2000)
				} else if (this.userinfo.boss == 1) {
					uni.navigateTo({
						url: "/pages/issueSelect/issueSelect"
					})
				} else if (this.userinfo.boss == -1) {
					uni.showToast({
						title: '您的认证信息还在审核中，请耐心等待',
						duration: 2000,
						icon: 'none'
					});
				}
			})
			uni.$on("logined", (d) => {
				this.userinfo = d;
				this.txConfig(this);
			})
			uni.$on("startLiveRoom", (d) => {
				this.target = d;
				this.startLiveRoom(this);
			})
			uni.$on("enterLiveRoom", (d) => {
				this.target = d;
				this.enterLiveRoom(this);
			})
			uni.$on("startCall", (d) => {
				this.target = d;
				this.txStartCall(this);
			})
			uni.$on("txCloseCall", () =>{
				this.txCloseCall();
			})
			uni.$on("updateConversationList", function(d) {
				console.log(d)
				let promise = this.tim.getConversationList();
				promise.then((res) => {
					let conversationList = res.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
					if (conversationList.length) {
						//将返回的会话列表拼接上 用户的基本资料  
						//说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
						this.$store.commit("updateConversationList", conversationList);
					}
				
				}).catch((err) => {
					console.warn('getConversationList error:', err); // 获取会话列表失败的相关信息
				});
			})

			if (this.userinfo !== undefined) {
				this.txConfig(this);
			}

		},
		onShow: function	() {
			console.log('App Show');
			if (this.liveStatus) {
				this.txCloseCall();
			}
			
		},
		onHide: function() {
			console.log('App Hide');
		}
	}
</script>

<style>
	/* 头条小程序需要把 iconfont 样式放到组件外 */
	@import "components/m-icon/m-icon.css";

	/*每个页面公共css */
	page {
		min-height: 100%;
		background-color: #FFFFFF;
	}
	.flex_start{
			display: flex;
			justify-content: flex-start;
			align-items: center;
		}
	.go_rob{
		width: 590rpx;
		height: 100rpx;
		margin:0 auto;
		line-height: 100rpx;
		text-align: center;
		font-size: 34rpx;
		color:#fff;
		background:linear-gradient(0deg,rgba(255,160,8,1),rgba(255,131,5,1));
		border-radius: 140rpx;
		margin-top:300rpx;
	}
	.distance{
		font-size: 22rpx;
		color: #999999;
	}
</style>
